package com.bigbigrain.jiagou.thread.five;

/**
 * @description: 生产者消费者
 * @author: B1gB1gRA1n
 * @create: 2020-3-27 11:31
 **/
public class ProduceAndConusumer {
}

class Data {
    private int num = 0;

    public static void main(String[] args) {
        Data data = new Data();
        new Thread(() -> {
            for (int i = 1; i <= 20; i++) {
                data.decrementNum();
            }
        }, "减少线程").start();
        new Thread(() -> {
            for (int i = 1; i <= 20; i++) {
                data.decrementNum();
            }
        }, "减少线程2").start();
        new Thread(() -> {
            for (int i = 1; i <= 20; i++) {
                data.incrementNum();
            }
        }, "增加线程").start();
        new Thread(() -> {
            for (int i = 1; i <= 20; i++) {
                data.incrementNum();
            }
        }, "增加线程2").start();
    }

    public synchronized void incrementNum() {
        while (num > 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //干活
        num++;
        System.out.println(Thread.currentThread().getName() + "\t" + num);
        //通知
        this.notifyAll();

    }

    public synchronized void decrementNum() {
        while (num == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //干活
        num--;
        System.out.println(Thread.currentThread().getName() + "\t" + num);
        //通知
        this.notifyAll();

    }
}